/**
 * https://leetcode.cn/problems/diameter-of-binary-tree/submissions/582602738/
 * 543. 二叉树的直径
 * easy 陈贝纯 2024.11.23
 * 换根dp
 */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int num=0;
    int  dfs(TreeNode* root){
        if(root==nullptr)
            return 0;
        int l=1+dfs(root->left);
        int r=1+dfs(root->right);
        num=max(num,r+l-1);
        return max(l,r);

    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return num-1;
    }
};